package com.jy.unkown.view;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.amjy.dsl.R;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.PlaybackPreparer;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.TrackGroupArray;
import com.google.android.exoplayer2.trackselection.TrackSelectionArray;
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.jy.common.BaseApplication;
import com.jy.unkown.DateUtil;
import com.jy.unkown.PlayProgressListener;
import com.jy.unkown.PlayStartPauseListener;
import com.jy.unkown.UnkownAdManager;
import com.jy.utils.utils.LogUtils;
import com.jy.utils.utils.UI;

import java.io.File;

public class UnkowVideoView extends PlayerView implements View.OnClickListener {

    private static final String TAG = "VideoPlayerView";


    PlayProgressListener playProgressListener;

    SimpleExoPlayer exoPlayer;
    private Handler handler = new Handler(Looper.getMainLooper());

    public UnkowVideoView(@NonNull Context context) {
        super(context);
        init(context);
        setUseController(false);
    }


    public UnkowVideoView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public UnkowVideoView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }


    public void setPlayProgressListener(PlayProgressListener playProgressListener) {
        this.playProgressListener = playProgressListener;
    }

    private void init(Context context) {
        if (isInEditMode()) {
            return;
        }

        initView(context);
        // 为SurfaceHolder添加回调

    }

    private void initView(Context context) {

    }


    private ExoPlayer.EventListener eventListener = new ExoPlayer.EventListener() {


        @Override
        public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
            Log.i(TAG, "onTracksChanged");
        }

        @Override
        public void onLoadingChanged(boolean isLoading) {
            Log.i(TAG, "onLoadingChanged");
        }

        boolean isLoaded = false;

        @Override
        public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
            Log.i(TAG, "onPlayerStateChanged: playWhenReady = " + String.valueOf(playWhenReady)
                    + " playbackState = " + playbackState);
            switch (playbackState) {
                case ExoPlayer.STATE_ENDED:
                    Log.i(TAG, "Playback ended!");
                    //Stop playback and return to start position
                    exoPlayer.seekTo(0);
                    exoPlayer.setPlayWhenReady(true);
                    break;
                case ExoPlayer.STATE_READY:
                    if (!isLoaded) {
                        if (exoPlayer != null) {
                            Log.i(TAG, "ExoPlayer ready! pos: " + exoPlayer.getCurrentPosition() + " max: "
                                    + "    exoPlayer.getDuration()=" + exoPlayer.getDuration());
                        }
                        isLoaded = true;
                        onPreparedListener.onPrepared(null);
                    }

                    break;
                case ExoPlayer.STATE_BUFFERING:
                    Log.i(TAG, "Playback buffering!");
                    break;
                case ExoPlayer.STATE_IDLE:
                    Log.i(TAG, "ExoPlayer idle!");
                    break;
            }
        }

        @Override
        public void onPlayerError(ExoPlaybackException error) {
            Log.i(TAG, "onPlaybackError: " + error.getMessage());
        }

    };

    /**
     * 播放本地视频
     *
     * @param mUrl
     */
    public void setUrl(String mUrl) {
        exoPlayer = new SimpleExoPlayer.Builder(getContext()).build();
        exoPlayer.addListener(eventListener);
        exoPlayer.setPlayWhenReady(false);
//        player.seekTo(currentWindow, playbackPosition);



        Uri playUri = Uri.parse(mUrl);
        MediaSource mediaSource = buildMediaSource(playUri);
        exoPlayer.prepare(mediaSource, true, false);
//        exoPlayer.setRepeatMode();
        exoPlayer.setRepeatMode(Player.REPEAT_MODE_ALL);
        setResizeMode(AspectRatioFrameLayout.RESIZE_MODE_FIXED_WIDTH);


        setPlayer(exoPlayer);
        setPlaybackPreparer(new PlaybackPreparer() {
            @Override
            public void preparePlayback() {
                Log.e(TAG, "preparePlayback");
            }
        });
        muteVoice(true);
    }

    private MediaSource buildMediaSource(Uri uri) {
        DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(getContext(), this.getContext().getPackageName());
        MediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
        return videoSource;
    }

    boolean mute;

    public void mute(boolean mute) {
        this.mute = mute;
    }

    public void playVideo() {
        exoPlayer.setPlayWhenReady(true);
    }


//    public MediaPlayer getMediaPlayer() {
//        return null;
//    }

    MediaPlayer.OnPreparedListener onPreparedListener;

    public void setOnPreparedListener(MediaPlayer.OnPreparedListener onPreparedListener) {
        this.onPreparedListener = onPreparedListener;
    }


    PlayStartPauseListener playStartPauseListener;

    public void setPlayStartPauseListener(PlayStartPauseListener playStartPauseListener) {
        this.playStartPauseListener = playStartPauseListener;
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.player) {

        }
    }


    public void destroy() {
        try {
            exoPlayer.release();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean isPlay() {
        if (exoPlayer != null) {
            boolean isPlaying = exoPlayer.isPlaying();
            return isPlaying;
        }
        return false;
    }

    public void muteVoice(boolean b) {
        mute = b;
        Player player = exoPlayer;
        if (player != null) {
            Player.AudioComponent audioComponent = exoPlayer.getAudioComponent();
            float volume = audioComponent.getVolume();
            if (volume != 0) {
                volume = 0;
            } else {
                volume = 1;

            }
            audioComponent.setVolume(volume);
        }

    }

}
